package com.ucomm.talent.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import android.os.Environment;

public class FileUtils {
	private String SDPATH;
	public String getSDPATH(){
		return SDPATH;
	}
	//获取外部存储设备目录
	public FileUtils(){
		SDPATH = Environment.getExternalStorageDirectory()+File.separator;
	}
	//在SD卡上创建目录
	public File creatSDDir(String dirName) {
		File dir = new File(SDPATH + dirName);
		dir.mkdirs();
		return dir;
	}
	/**
	 * 在SD卡上创建文件
	 * 
	 * @throws IOException
	 */
	public File creatSDFile(String fileName) throws IOException {
		File file = new File(SDPATH + fileName);
		file.createNewFile();
		return file;
	}
	/**
	 * 判断SD卡上的文件夹是否存在
	 */
	public boolean isFileExist(String fileName){
		File file = new File(SDPATH + fileName);
		return file.exists();
	}
	/**
	 * 将一个Map数据写入到SD卡中
	 */
	public File write2SDFromMap(String dirName,String fileName,HashMap<String, String> map){
		File file = null;
		FileOutputStream output = null;
		ObjectOutputStream objectOutputStream = null;
		String path = null;
		try{
			if(!isFileExist(dirName)){
				creatSDDir(dirName);
			}
			path = dirName + File.separator + fileName;
			file = creatSDFile(path);
			output = new FileOutputStream(file);
			objectOutputStream = new ObjectOutputStream(output);
			objectOutputStream.writeObject(map);
			System.out.println("success------------>");
			objectOutputStream.flush();
			output.flush();

		}
		catch(Exception e){
			e.printStackTrace();
		}
		finally{
			try{
				objectOutputStream.close();
				output.close();
			}
			catch(Exception e){
				e.printStackTrace();
			}
		}
		return file;
	}
	/**
	 * 从SDcard中获取Map数据
	 */
	public HashMap<String, String> readMapFromSD (String dirName,String fileName){
		String filepath = null;
		FileInputStream input = null;
		ObjectInputStream objectInputStream = null;
		HashMap<String, String> map = new HashMap<String, String>();
		try{
			filepath = getSDPATH()+dirName+File.separator+fileName;
			input = new FileInputStream(filepath);
			objectInputStream = new ObjectInputStream(input);
			map = (HashMap<String, String>) objectInputStream.readObject();
			
		}
		catch(Exception e){
			e.printStackTrace();
		}
		finally{
			try{
				objectInputStream.close();
				input.close();
			}
			catch(Exception e){
				e.printStackTrace();
			}
		}
		return map;
	}
}
